import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:geocoding/geocoding.dart';
import 'package:geolocator/geolocator.dart';

class FMLocationManager {

  static final FMLocationManager _instance = FMLocationManager._internal();

  factory FMLocationManager() => _instance;

  FMLocationManager._internal();

  StreamSubscription<Position>? _positionStream;

  Placemark? _placemark;
  Position? _position;

  LocationSettings get _settings => const LocationSettings(
    accuracy: LocationAccuracy.best,
    distanceFilter: 0,
  );

  // 获取位置信息
  Future<void> startLocation() async {
    // 检查权限
    bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      throw Exception('Location services are disabled');
    }

    LocationPermission permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        throw Exception('Location permissions are denied');
      }
    }

    _position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.best);
    _positionStream = Geolocator.getPositionStream(locationSettings: _settings)
        .listen((Position position) {
      _position = position;
      _reverseGeocode(position);
    });
  }

  // 反向地理编码
  Future<void> _reverseGeocode(Position position) async {
    try {
      List<Placemark> placeMarks = await placemarkFromCoordinates(
          position.latitude,
          position.longitude
      );
      _placemark = placeMarks.first;
      // 通知其他模块（示例）
    } catch (e) {
      if (kDebugMode) {
        print("Geocoding error: $e");
      }
    }
  }

  void dispose() {
    _positionStream?.cancel(); // 关闭定位流[2]
  }

  // 获取最后位置
  Position? get location => _position;

  // 获取地理编码信息
  Placemark? get placeMark => _placemark;
}